﻿using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Oliving.Edge.Common;
using Oliving.Edge.Common.DB;
using Oliving.Edge.Common.Helper;
using Oliving.Edge.Model.Models;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace Oliving.Edge.Model.Seed
{

    public class EdgeContext
    {

        public void EdgeGetData(
         string strPathBath,
         string[] lstTableNames,
         string strInterface)
        {
            List<RazorTableInfo> tableList = EdgeGetRazorTableInfoList(lstTableNames);

            var seChar = Path.DirectorySeparatorChar.ToString();
            IsoDateTimeConverter timeConverter = new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" };
            foreach (RazorTableInfo item in tableList)
            {
                System.Data.DataTable dt = _db.Ado.GetDataTable(" select * from " + item.DbTableName);
                string JsonString = JsonConvert.SerializeObject(dt, Formatting.Indented, timeConverter);

                var filePath = strPathBath.TrimEnd('\\').TrimEnd('/') + string.Format(seChar + "{0}.tsv",
                    item.DbTableName);

                System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); // 当地时区

                long timeStamp = (long)(DateTime.Now - startTime).TotalMilliseconds; // 相差毫秒数

                System.Console.WriteLine(timeStamp);

                FileHelper.CreateFile(filePath, JsonString, Encoding.UTF8);
            }
        }

        #region Base


        #region MyRegion

        private static MutiDBOperate connectObject => GetMainConnectionDb();
        private static string _connectionString = connectObject.Conn;
        private static DbType _dbType = (DbType)connectObject.DbType;
        private SqlSugarClient _db;

        /// <summary>
        /// 连接字符串 
        /// Oliving.Edge
        /// </summary>
        public static MutiDBOperate GetMainConnectionDb()
        {
            var mainConnetctDb = BaseDBConfig.MutiConnectionString.Find(x => x.ConnId == MainDb.CurrentDbConnId);
            if (BaseDBConfig.MutiConnectionString.Count > 0)
            {
                if (mainConnetctDb == null)
                {
                    mainConnetctDb = BaseDBConfig.MutiConnectionString[0];
                }
            }
            else
            {
                throw new Exception("请确保appsettigns.json中配置连接字符串,并设置Enabled为true;");
            }

            return mainConnetctDb;
        }
        /// <summary>
        /// 连接字符串 
        /// Oliving.Edge
        /// </summary>
        public static string ConnectionString
        {
            get { return _connectionString; }
            set { _connectionString = value; }
        }
        /// <summary>
        /// 数据库类型 
        /// Oliving.Edge 
        /// </summary>
        public static DbType DbType
        {
            get { return _dbType; }
            set { _dbType = value; }
        }
        /// <summary>
        /// 数据连接对象 
        /// Oliving.Edge 
        /// </summary>
        public SqlSugarClient Db
        {
            get { return _db; }
            private set { _db = value; }
        }

        /// <summary>
        /// 数据库上下文实例（自动关闭连接）
        /// Oliving.Edge 
        /// </summary>
        public static EdgeContext Context
        {
            get
            {
                return new EdgeContext();
            }

        }


        /// <summary>
        /// 功能描述:构造函数
        /// 作　　者:Oliving.Edge
        /// </summary>
        public EdgeContext()
        {
            if (string.IsNullOrEmpty(_connectionString))
                throw new ArgumentNullException("数据库连接字符串为空");
            _db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = _connectionString,
                DbType = _dbType,
                IsAutoCloseConnection = true,
                InitKeyType = InitKeyType.Attribute,//mark
                ConfigureExternalServices = new ConfigureExternalServices()
                {
                    //DataInfoCacheService = new HttpRuntimeCache()
                },
                MoreSettings = new ConnMoreSettings()
                {
                    //IsWithNoLockQuery = true,
                    IsAutoRemoveDataCache = true
                }
            });
        }



        #endregion

        #region 参数

        public static string UsingTemplate = "using System;\r\n" +
                                             "using System.Linq;\r\n" +
                                             "using System.Text;" + "\r\n";
        public static string UsingTemplateSugar = "using System;\r\n" +
                                              "using System.Linq;\r\n" +
                                              "using System.Text;" + "\r\n" +
                                              "using SqlSugar;" + "\r\n";
        #endregion

        #region 实例方法
        /// <summary>
        /// 功能描述:获取数据库处理对象
        /// 作　　者:Oliving.Edge
        /// </summary>
        /// <returns>返回值</returns>
        public SimpleClient<T> GetEntityDB<T>() where T : class, new()
        {
            return new SimpleClient<T>(_db);
        }
        /// <summary>
        /// 功能描述:获取数据库处理对象
        /// 作　　者:Oliving.Edge
        /// </summary>
        /// <param name="db">db</param>
        /// <returns>返回值</returns>
        public SimpleClient<T> GetEntityDB<T>(SqlSugarClient db) where T : class, new()
        {
            return new SimpleClient<T>(db);
        }



        #endregion

        #region 根据实体类生成数据库表
        /// <summary>
        /// 功能描述:根据实体类生成数据库表
        /// 作　　者:Oliving.Edge
        /// </summary>
        /// <param name="blnBackupTable">是否备份表</param>
        /// <param name="lstEntitys">指定的实体</param>
        public void CreateTableByEntity<T>(bool blnBackupTable, params T[] lstEntitys) where T : class, new()
        {
            Type[] lstTypes = null;
            if (lstEntitys != null)
            {
                lstTypes = new Type[lstEntitys.Length];
                for (int i = 0; i < lstEntitys.Length; i++)
                {
                    T t = lstEntitys[i];
                    lstTypes[i] = typeof(T);
                }
            }
            CreateTableByEntity(blnBackupTable, lstTypes);
        }

        /// <summary>
        /// 功能描述:根据实体类生成数据库表
        /// 作　　者:Oliving.Edge
        /// </summary>
        /// <param name="blnBackupTable">是否备份表</param>
        /// <param name="lstEntitys">指定的实体</param>
        public void CreateTableByEntity(bool blnBackupTable, params Type[] lstEntitys)
        {
            if (blnBackupTable)
            {
                _db.CodeFirst.BackupTable().InitTables(lstEntitys); //change entity backupTable            
            }
            else
            {
                _db.CodeFirst.InitTables(lstEntitys);
            }
        }
        #endregion

        #region 静态方法

        /// <summary>
        /// 功能描述:获得一个DbContext
        /// 作　　者:Oliving.Edge
        /// </summary>
        /// <returns></returns>
        public static EdgeContext GetDbContext()
        {
            return new EdgeContext();
        }

        /// <summary>
        /// 功能描述:设置初始化参数
        /// 作　　者:Oliving.Edge
        /// </summary>
        /// <param name="strConnectionString">连接字符串</param>
        /// <param name="enmDbType">数据库类型</param>
        public static void Init(string strConnectionString, DbType enmDbType = SqlSugar.DbType.SqlServer)
        {
            _connectionString = strConnectionString;
            _dbType = enmDbType;
        }

        /// <summary>
        /// 功能描述:创建一个链接配置
        /// 作　　者:Oliving.Edge
        /// </summary>
        /// <param name="blnIsAutoCloseConnection">是否自动关闭连接</param>
        /// <param name="blnIsShardSameThread">是否夸类事务</param>
        /// <returns>ConnectionConfig</returns>
        public static ConnectionConfig GetConnectionConfig(bool blnIsAutoCloseConnection = true, bool blnIsShardSameThread = false)
        {
            ConnectionConfig config = new ConnectionConfig()
            {
                ConnectionString = _connectionString,
                DbType = _dbType,
                IsAutoCloseConnection = blnIsAutoCloseConnection,
                ConfigureExternalServices = new ConfigureExternalServices()
                {
                    //DataInfoCacheService = new HttpRuntimeCache()
                },
                IsShardSameThread = blnIsShardSameThread
            };
            return config;
        }

        /// <summary>
        /// 功能描述:获取一个自定义的DB
        /// 作　　者:Oliving.Edge
        /// </summary>
        /// <param name="config">config</param>
        /// <returns>返回值</returns>
        public static SqlSugarClient GetCustomDB(ConnectionConfig config)
        {
            return new SqlSugarClient(config);
        }
        /// <summary>
        /// 功能描述:获取一个自定义的数据库处理对象
        /// 作　　者:Oliving.Edge
        /// </summary>
        /// <param name="sugarClient">sugarClient</param>
        /// <returns>返回值</returns>
        public static SimpleClient<T> GetCustomEntityDB<T>(SqlSugarClient sugarClient) where T : class, new()
        {
            return new SimpleClient<T>(sugarClient);
        }
        /// <summary>
        /// 功能描述:获取一个自定义的数据库处理对象
        /// 作　　者:Oliving.Edge
        /// </summary>
        /// <param name="config">config</param>
        /// <returns>返回值</returns>
        public static SimpleClient<T> GetCustomEntityDB<T>(ConnectionConfig config) where T : class, new()
        {
            SqlSugarClient sugarClient = GetCustomDB(config);
            return GetCustomEntityDB<T>(sugarClient);
        }
        #endregion


        #endregion

        ////////////////////

        #region Edge

        /// <summary>
        /// 获取数据库要生成表的数据model配置
        /// </summary> 
        /// <param name="lstTableNames"></param> 
        /// <returns></returns>
        public List<RazorTableInfo> EdgeGetRazorTableInfoList(
          string[] lstTableNames)
        {

            var IDbFirst = _db.DbFirst;



            List<RazorTableInfo> razorList = new List<RazorTableInfo>();

            if (lstTableNames != null && lstTableNames.Length > 0)
            {
                IDbFirst = IDbFirst.Where(lstTableNames);
            }

            var tables = IDbFirst.Context.DbMaintenance.GetTableInfoList(false);

            if (tables.HasValue())
            {
                foreach (var item in tables)
                {
                    if ((lstTableNames.Length == 0) || lstTableNames.Contains(item.Name))
                    {

                        var columns = IDbFirst.Context.DbMaintenance.GetColumnInfosByTableName(item.Name, false);
                        RazorTableInfo table = new RazorTableInfo()
                        {
                            Columns = columns.Select(it => new RazorColumnInfo()
                            {
                                ColumnDescription = it.ColumnDescription,
                                DataType = it.DataType,
                                DbColumnName = it.DbColumnName,
                                DefaultValue = it.DefaultValue,
                                IsIdentity = it.IsIdentity,
                                IsNullable = it.IsNullable,
                                IsPrimarykey = it.IsPrimarykey,
                                Length = it.Length
                            }).ToList(),
                            Description = item.Description,
                            DbTableName = item.Name
                        };
                        foreach (var col in table.Columns)
                        {
                            col.DataType = GetPropertyTypeName(columns.First(it => it.DbColumnName == col.DbColumnName));
                        }
                        razorList.Add(table);
                    }
                }
            }

            return razorList;
        }



        private string GetPropertyTypeName(DbColumnInfo item)
        {


            var IDbFirst = _db.DbFirst;
            string result = item.PropertyType != null ? item.PropertyType.Name : IDbFirst.Context.Ado.DbBind.GetPropertyTypeName(item.DataType);
            if (result != "string" && result != "byte[]" && result != "object" && item.IsNullable)
            {
                result += "?";
            }
            if (result == "Int32")
            {
                result = "int";
            }
            if (result == "String")
            {
                result = "string";
            }
            return result;
        }

        #endregion

        #region Create Code

        /// <summary>
        /// 
        /// 1 、 2020年4月3日14:04:24 
        ///      autoMapper 代码
        ///      表名条件
        ///      自定义方法 QueryPageList
        /// </summary>
        /// <param name="strPathBath">C:\my-file\</param>
        /// <param name="strNameSpace"></param>
        /// <param name="lstTableNames"></param>
        /// <param name="strInterface"></param>
        /// <param name="SuffixName"></param>
        /// <param name="blnSerializable"></param>
        public void EdgeCreateClass(string strPathBath, string[] lstTableNames, string productCode = "")
        {
            string strInterface = "";
            string SuffixName = "";
            bool blnSerializable = false;
            //string strNameSpace,
            List<RazorTableInfo> tableList = EdgeGetRazorTableInfoList(lstTableNames);

            //tableList = tableList.Where(T => lstTableNames.Contains(T.DbTableName)).ToList();

            if (!string.IsNullOrEmpty(productCode)) { productCode = "." + productCode; }


            #region Base

            EdgeCreate_Model_ClassFileByDBTalbe(
                strPathBath + "Oliving.Edge.Model" + productCode,
                "Oliving.Edge.Model.Models" + productCode,
                strInterface,
                tableList,
                SuffixName, blnSerializable, 0);

            EdgeCreate_IRepository(
                strPathBath + "Oliving.Edge.IRepository" + productCode, "Oliving.Edge.IRepository" + productCode,
                productCode,
                strInterface,
                tableList,
                SuffixName);

            EdgeCreate_IServices(
                strPathBath + "Oliving.Edge.IServices" + productCode, "Oliving.Edge.IServices" + productCode,
                productCode,
                strInterface,
                tableList);

            EdgeCreate_Repository(
                strPathBath + "Oliving.Edge.Repository" + productCode, "Oliving.Edge.Repository" + productCode,
                productCode,
                strInterface,
                tableList);

            EdgeCreate_Services(
                strPathBath + "Oliving.Edge.Services" + productCode, "Oliving.Edge.Services" + productCode,
                productCode,
                strInterface,
                tableList);


            #endregion

            #region Dto


            EdgeCreate_Model_ClassFileByDBTalbe(
                strPathBath + "Oliving.Edge.Model.Dto" + productCode, "Oliving.Edge.Model.Dto" + productCode,
                strInterface,
                tableList,
                "Dto", blnSerializable, 1);
            EdgeCreate_Model_ClassFileByDBTalbe(
                strPathBath + "Oliving.Edge.Model.Dto" + productCode, "Oliving.Edge.Model.Dto" + productCode,
                strInterface,
                tableList,
                "PageDto", blnSerializable, 1);

            #endregion


            EdgeCreate_Controller(
                  strPathBath + "Oliving.Edge.Controllers", "Oliving.Edge.Controllers",
                  strInterface,
                  tableList, true);

            EdgeCreate_VueView(
                  strPathBath + "Oliving.Edge.VueView", "Oliving.Edge.VueView",
                  strInterface,
                  tableList, true);

            EdgeCreate_VueApi(strPathBath + "Oliving.Edge.VueView", tableList);

            EdgeCreate_AutoMapper(strPathBath + "Oliving.Edge.AutoMapper", tableList);
        }


        #endregion

        #region 代码生成器 new

        #region 生成model

        /// <summary>
        /// 生成model 
        /// </summary> 
        public void EdgeCreate_Model_ClassFileByDBTalbe(
           string strPath,
           string strNameSpace,
           string strInterface,
           List<RazorTableInfo> tableList,
           string SuffixName = "",
           bool blnSerializable = false,
           int type = 0)
        {

            var seChar = Path.DirectorySeparatorChar.ToString();

            strInterface = (string.IsNullOrEmpty(strInterface) ? "" : (" : " + strInterface));

            foreach (RazorTableInfo item in tableList)
            {
                #region 模板

                string classText = @"   
{using}  
 namespace " + strNameSpace + @"
{
    ///<summary>
    ///{ClassDescription}
    ///</summary> 
    {SugarTable}
    [Serializable]
    public class {ClassName}{SuffixName} {strInterface}
    {
        public {ClassName}{SuffixName}()
        {
        }
        {PropertyName}
    }

}
";


                #endregion

                #region Column

                string propertyText = "";
                foreach (RazorColumnInfo col in item.Columns)
                {
                    string PropertyDescription = col.ColumnDescription;
                    string DefaultValue = col.DefaultValue;
                    string IsNullable = col.IsNullable.ToString();

                    string colName = col.DbColumnName;
                    string colDataType = col.DataType;


                    string SugarColumnText = "";

                    #region SugarColumnText

                    List<string> joinList = new List<string>();


                    if (col.IsPrimarykey)
                    {
                        joinList.Add("IsPrimaryKey=true");
                    }
                    if (col.IsIdentity)
                    {
                        joinList.Add("IsIdentity=true");
                    }
                    if (!string.IsNullOrEmpty(col.DbColumnName))
                    {
                        joinList.Add("ColumnName=\"" + col.DbColumnName + "\"");
                    }
                    if (!string.IsNullOrEmpty(col.ColumnDescription))
                    {
                        joinList.Add("ColumnDescription=\"" + col.ColumnDescription + "\"");
                    }
                    if (col.IsNullable)
                    {
                        joinList.Add("IsNullable=true");
                    }

                    if (colDataType.ToLower().Equals("string".ToLower()))
                    {
                        if (col.Length > 0)
                        {
                            joinList.Add("Length=" + col.Length + "");
                        }

                        joinList.Add("ColumnDataType=\"nvarchar\"");

                    }

                    #endregion

                    string Col_ValidationAttribute = "";
                    if (col.IsNullable)
                    {
                        string ValidationText = "";


                        if (!string.IsNullOrEmpty(col.DbColumnName))
                        {
                            ValidationText = col.DbColumnName;
                        }
                        if (!string.IsNullOrEmpty(col.ColumnDescription))
                        {
                            ValidationText = col.ColumnDescription;
                        }



                        switch (colDataType)
                        {
                            case "string":
                                if (col.Length > 0)
                                {
                                    Col_ValidationAttribute = "[StringLength(" + col.Length + ", MinimumLength = 1, ErrorMessage = \"" + ValidationText + "不能为空,内存长度超出 范围\")]";
                                }
                                else
                                {
                                    Col_ValidationAttribute = "[Required(ErrorMessage = \"" + ValidationText + "不能为空\")]";
                                }
                                break;
                            case "int":
                                // Col_ValidationAttribute = "[Range(1, 100, ErrorMessage = \"年龄必须介于1~100之间\")]";
                                break;

                            case "DateTime":
                                Col_ValidationAttribute = " [DisplayName(\"" + ValidationText + "\")] "
                                                           + " [DataType(DataType.DateTime, ErrorMessage = \"请以dd / mm / yyyy hh: mm格式输入有效日期\")] "
                                                           + " [Range(typeof(DateTime), \"1/1/1753\", \"12/31/9999\")]";
                                break;
                        }
                    }




                    SugarColumnText = string.Format(DbFirstTemplate.ValueSugarCoulmn, string.Join(",", joinList));

                    string propertyItem = @"   
                            /// <summary> 
                            /// Desc:{PropertyDescription} 
                            /// Default:{DefaultValue} 
                            /// Nullable:{IsNullable} 
                            /// </summary> 
                            {SugarColumnText}
                            public {colDataType} {colName} { get; set; } 
 ";

                    propertyItem = propertyItem.Replace("{PropertyDescription}", PropertyDescription);
                    propertyItem = propertyItem.Replace("{DefaultValue}", DefaultValue);
                    propertyItem = propertyItem.Replace("{IsNullable}", IsNullable);

                    propertyItem = propertyItem.Replace("{colDataType}", colDataType);
                    propertyItem = propertyItem.Replace("{colName}", colName);


                    if (type == 0)
                    {
                        propertyItem = propertyItem.Replace("{SugarColumnText}", SugarColumnText);
                    }
                    else if (type == 1)
                    {
                        propertyItem = propertyItem.Replace("{SugarColumnText}", Col_ValidationAttribute);
                    }


                    propertyText = propertyText + propertyItem;
                }

                #endregion

                #region 替换字符串

                if (type == 0)
                {
                    classText = classText.Replace(DbFirstTemplate.KeyUsing, UsingTemplateSugar);
                    classText = classText.Replace(DbFirstTemplate.KeySugarTable, string.Format(DbFirstTemplate.ValueSugarTable, item.DbTableName));
                }
                else if (type == 1)
                {
                    classText = classText.Replace(DbFirstTemplate.KeyUsing, UsingTemplate + @"
using System.ComponentModel.DataAnnotations;
");
                    classText = classText.Replace(DbFirstTemplate.KeySugarTable, "");
                }


                #region 替换字符串 Base

                classText = classText.Replace(DbFirstTemplate.KeyClassDescription, item.Description);

                classText = classText.Replace("{ClassName}", item.DbTableName);
                classText = classText.Replace("{SuffixName}", SuffixName);
                classText = classText.Replace("{strInterface}", strInterface);
                classText = classText.Replace("{PropertyName}", propertyText);
                #endregion

                #endregion

                var filePath = strPath.TrimEnd('\\').TrimEnd('/') + string.Format(seChar + "{0}{1}.cs", item.DbTableName, SuffixName);
                FileHelper.CreateFile(filePath, classText, Encoding.UTF8);
            }

        }
        #endregion

        #region 根据数据库表生产IRepository层

        /// <summary>
        /// 功能描述:根据数据库表生产IRepository层
        /// 作　　者:Oliving.Edge
        /// </summary>
        /// <param name="strPath">实体类存放路径</param>
        /// <param name="strNameSpace">命名空间</param>
        /// <param name="lstTableNames">生产指定的表</param>
        /// <param name="strInterface">实现接口</param>
        /// <param name="tableList"></param>
        /// <param name="SuffixName"></param>
        public void EdgeCreate_IRepository(
          string strPath, string strNameSpace, string productCode, string strInterface,
          List<RazorTableInfo> tableList, string SuffixName = "")
        {
            var seChar = Path.DirectorySeparatorChar.ToString();
            foreach (RazorTableInfo item in tableList)
            {

                string classText = @"   
using System;
using System.Threading.Tasks;
using System.Linq.Expressions;


using Oliving.Edge.IRepository.Base;
using Oliving.Edge.Model;" + "\r\n"
+ @"using Oliving.Edge.Model.Dto" + productCode + ";\r\n"
+ @"using Oliving.Edge.Model" + productCode + ";\r\n"
+ @"
" + @"
 namespace " + strNameSpace + @"
{
	/// <summary>
	/// I{ClassName}Repository  , {ClassName} , {Description}
	/// </summary>	
    public interface I{ClassName}Repository : IBaseRepository<{ClassName}>" + (string.IsNullOrEmpty(strInterface) ? "" : (" , " + strInterface)) + @"
    { "

+ EdgeCreate_IRepository_QueryPageList()

+ @" 
    }
        }
";
                classText = classText.Replace("{ClassName}", item.DbTableName);
                classText = classText.Replace("{Description}", item.Description);

                var filePath = strPath.TrimEnd('\\').TrimEnd('/') + string.Format(seChar + "I{0}Repository.cs", item.DbTableName);
                FileHelper.CreateFile(filePath, classText, Encoding.UTF8);

            }

        }

        private string EdgeCreate_IRepository_QueryPageList()
        {
            return "      Task<PageModel<{ClassName}PageDto>> QueryPageList(Expression<Func<{ClassName}, bool>> whereExpression, int intPageIndex = 1, int intPageSize = 20, string sortField = null, string sortOrder = null);";
        }


        #endregion

        #region 根据数据库表生产IServices层

        /// <summary>
        /// 功能描述:根据数据库表生产IServices层
        /// 作　　者:Oliving.Edge
        /// </summary>
        /// <param name="strPath">实体类存放路径</param>
        /// <param name="strNameSpace">命名空间</param>
        /// <param name="lstTableNames">生产指定的表</param>
        /// <param name="strInterface">实现接口</param>
        public void EdgeCreate_IServices(
          string strPath,
          string strNameSpace,
          string productCode,
          string strInterface,
          List<RazorTableInfo> tableList)
        {
            foreach (RazorTableInfo item in tableList)
            {

                string classText = @"   

using System;
using System.Threading.Tasks;
using System.Linq.Expressions;
 
using Oliving.Edge.IServices.BASE;
using Oliving.Edge.Model;" + "\r\n"
+ @"using Oliving.Edge.Model.Dto" + productCode + ";\r\n"
+ @"using Oliving.Edge.Model" + productCode + ";\r\n"
+ @"
" + @"


namespace " + strNameSpace + @"
{	
	/// <summary>
	/// I{ClassName}Services , {Description}
	/// </summary>	
    public interface I{ClassName}Services :IBaseServices<{ClassName}>" + (string.IsNullOrEmpty(strInterface) ? "" : (" , " + strInterface)) + @"
	{
" + EdgeCreate_IServices_QueryPageList() + @"
       
    }
}
                 
";
                classText = classText.Replace("{ClassName}", item.DbTableName);
                classText = classText.Replace("{Description}", item.Description);

                var filePath = strPath.TrimEnd('\\').TrimEnd('/') + string.Format(Path.DirectorySeparatorChar.ToString() + "I{0}Services.cs", item.DbTableName);
                FileHelper.CreateFile(filePath, classText, Encoding.UTF8);

            }
            //============================================================


        }


        public string EdgeCreate_IServices_QueryPageList()
        {

            string functionText = @"   

            /// <summary>
            /// 自定义分页查询
            /// </summary>
            /// <param name=""whereExpression"" > 查询条件</param>
            /// <param name=""pageIndex"" > 页码</param>
            /// <param name=""pageSize"" > 页大小</param>
            /// <param name=""sortField"" > 排序字段</param>
            /// <param name=""sortOrder"" > 排序 （asc/desc）</param>
            /// <returns></returns>
            Task < PageModel<{ClassName}PageDto>> QueryPageList(
            Expression<Func<{ClassName}, bool>> whereExpression,
            int PageIndex = 1,
            int PageSize = 20,
            string sortField = null,
            string sortOrder = null);

            ";

            return functionText;
        }




        #endregion

        #region 根据数据库表生产 Repository 层

        /// <summary>
        /// 功能描述:根据数据库表生产 Repository 层
        /// 作　　者:Oliving.Edge
        /// </summary>
        /// <param name="strPath">实体类存放路径</param>
        /// <param name="strNameSpace">命名空间</param>
        /// <param name="lstTableNames">生产指定的表</param>
        /// <param name="strInterface">实现接口</param>
        public void EdgeCreate_Repository(
          string strPath,
          string strNameSpace,
          string productCode,
          string strInterface,
          List<RazorTableInfo> tableList)
        {
            foreach (RazorTableInfo item in tableList)
            {
                string classText = @"   
using System;
using SqlSugar;
using System.Threading.Tasks;
using System.Linq.Expressions; 

using Oliving.Edge.Model;
using Oliving.Edge.Model.Dto;
using Oliving.Edge.Model.Models;
using Oliving.Edge.IRepository;
using Oliving.Edge.IRepository.UnitOfWork;
using Oliving.Edge.Repository.Base;" + "\r\n"

+ @"using Oliving.Edge.Model.Dto" + productCode + ";\r\n"
+ @"using Oliving.Edge.Model" + productCode + ";\r\n"
+ @"using Oliving.Edge.IRepository" + productCode + ";\r\n"
+ @"
" + @"



namespace " + strNameSpace + @"
{
	/// <summary>
	/// {ClassName}Repository
	/// </summary>
    public class {ClassName}Repository : BaseRepository<{ClassName}>, I{ClassName}Repository" + (string.IsNullOrEmpty(strInterface) ? "" : (" , " + strInterface)) + @"
    {
        public {ClassName}Repository(IUnitOfWork unitOfWork) : base(unitOfWork)
        {
        }
" + EdgeCreate_Repository_QueryPageList(item.DbTableName) + @"

    }
}
                 
";

                classText = classText.Replace("{ClassName}", item.DbTableName);
                classText = classText.Replace("{Description}", item.Description);

                var filePath = strPath.TrimEnd('\\').TrimEnd('/') + string.Format(Path.DirectorySeparatorChar.ToString() + "{0}Repository.cs", item.DbTableName);
                FileHelper.CreateFile(filePath, classText, Encoding.UTF8);
            }
        }

        private string EdgeCreate_Repository_QueryPageList(string ClassName)
        {
            string functionText = @"   





             /// <summary>
             /// 自定义分页查询
             /// </summary>
             /// <param name=""whereExpression"">查询条件</param>
             /// <param name=""pageIndex"" > 页码（下标0）</param>
             /// <param name=""pageSize"" > 页大小</param>
             /// <param name=""sortField"" > 排序字段</param>
             /// <param name=""sortOrder"" > 排序顺序（asc/desc）</param>
             /// <returns></returns>
            public async Task<PageModel<{ClassName}PageDto>> QueryPageList(
                    Expression<Func<{ClassName}, bool>> whereExpression,
                    int pageIndex = 1, int pageSize = 20,
                    string sortField = null, string sortOrder = null
                    )
            {


                #region 排序

                string strOrderByFileds = null;

                if (!string.IsNullOrEmpty(sortField))
                {
                    strOrderByFileds = sortField;
                    if (sortOrder != null && sortOrder.ToLower().Contains(""desc""))
                    {
                        strOrderByFileds = strOrderByFileds + "" desc"";
                    }
                    else
                    {
                        strOrderByFileds = strOrderByFileds + "" asc"";
                    }
                }

                #endregion

                if (1 == 1)
                {
                    #region 单表

                    RefAsync<int> totalCount = 0;
                    var list = await Db.Queryable<{ClassName}>()
                             .OrderByIF(!string.IsNullOrEmpty(strOrderByFileds), strOrderByFileds)
                             .WhereIF(whereExpression != null, whereExpression)
                             .Select<{ClassName}PageDto>()
                             .ToPageListAsync(pageIndex, pageSize, totalCount);

                    int pageCount = (Math.Ceiling(totalCount.ObjToDecimal() / pageSize.ObjToDecimal())).ObjToInt();
                    return new PageModel<{ClassName}PageDto>()
                    {
                        dataCount = totalCount,
                        pageCount = pageCount,
                        page = pageIndex,
                        PageSize = pageSize,
                        data = list
                    };

                    #endregion
                }

                {
                    //var list = Db.Queryable<DTSN_Canning, DTSN_TongDao>
                    //   ((c, td) => new object[] { JoinType.Left, c.Canning_TongDaoID == td.TD_ID })
                    // //.OrderByIF(!string.IsNullOrEmpty(strOrderByFileds), strOrderByFileds)
                    // .WhereIF(whereExpression != null, whereExpression)
                    // .GroupBy((c, td) => td.TD_Type)
                    // .GroupBy((c, td) => Convert.ToDateTime(c.Canning_BeginTime).ToShortDateString())
                    //   .Select((c, td) => new
                    //   {
                    //       date = Convert.ToDateTime(c.Canning_BeginTime).ToShortDateString(),
                    //       type = td.TD_Type,
                    //       sum = SqlFunc.AggregateSum(c.Canning_NetWeight)
                    //   }).ToList();
                }


            }



 
           
            ";

            functionText = functionText.Replace("{ClassName}", ClassName);

            return functionText;
        }



        #endregion

        #region 根据数据库表生产 Services 层

        /// <summary>
        /// 功能描述:根据数据库表生产 Services 层
        /// 作　　者:Oliving.Edge
        /// </summary>
        /// <param name="strPath">实体类存放路径</param>
        /// <param name="strNameSpace">命名空间</param> 
        /// <param name="strInterface">实现接口</param>
        public void EdgeCreate_Services(
          string strPath,
          string strNameSpace,
          string productCode,
          string strInterface,
          List<RazorTableInfo> tableList)
        {
            foreach (RazorTableInfo item in tableList)
            {
                string classText = @"   
 
using System;
using System.Threading.Tasks;
using System.Linq.Expressions;
 
using Oliving.Edge.Model;
using Oliving.Edge.Model.Dto;
using Oliving.Edge.Model.Models;
using Oliving.Edge.IServices;
using Oliving.Edge.IRepository;
using Oliving.Edge.Services.BASE;" + "\r\n"

+ @"using Oliving.Edge.Model.Dto" + productCode + ";\r\n"
+ @"using Oliving.Edge.Model" + productCode + ";\r\n"
+ @"using Oliving.Edge.IRepository" + productCode + ";\r\n"
+ @"using Oliving.Edge.IServices" + productCode + ";\r\n"
+ @"
" + @"


namespace " + strNameSpace + @"{
                public partial class {ClassName}Services : BaseServices<{ClassName}>, I{ClassName}Services"
        + (string.IsNullOrEmpty(strInterface) ? "" : (" , " + strInterface)) + @"
    {
        I{ClassName}Repository _dal;
        public {ClassName}Services(I{ClassName}Repository dal)
        {
            this._dal = dal;
            base.BaseDal = dal;
        } 
" + EdgeCreate_Services_QueryPageList() + @"

    }
}
     
";

                classText = classText.Replace("{ClassName}", item.DbTableName);
                classText = classText.Replace("{Description}", item.Description);

                var filePath = strPath.TrimEnd('\\').TrimEnd('/')
                    + string.Format(Path.DirectorySeparatorChar.ToString() + "{0}Services.cs", item.DbTableName);
                FileHelper.CreateFile(filePath, classText, Encoding.UTF8);
            }

        }



        public string EdgeCreate_Services_QueryPageList()
        {

            string functionText = @"    
               

        public async Task<PageModel<{ClassName}PageDto>> QueryPageList(
            Expression<Func<{ClassName}, bool>> whereExpression,
            int pageIndex = 1, int pageSize = 20,
            string sortField = null, string sortOrder = null
            )
        {
            var page = await _dal.QueryPageList(
                whereExpression,
                pageIndex, pageSize,
                    sortField, sortOrder);
            return page;
        }
 
            ";

            return functionText;
        }

        #endregion


        #endregion

        //  ================================================================

        #region Control

        public void EdgeCreate_Controller(
          string strPath,
          string strNameSpace,
          string strInterface,
          List<RazorTableInfo> tableList, bool isControllerBase = false)
        {
            string baseCotroll = isControllerBase ? "OlivingControll" : "ControllerBase";



            foreach (RazorTableInfo item in tableList)
            {
                RazorColumnInfo pkCol = item.Columns.FirstOrDefault(F => F.IsPrimarykey);
                string pkColName = pkCol.DbColumnName;

                string classText = @"   
 
using System;
using AutoMapper;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Authorization;

using Oliving.Edge.AuthHelper; 
using Oliving.Edge.Model;
using Oliving.Edge.Model.Models; 
using Oliving.Edge.IServices;
using Oliving.Edge.Model.Dto;

namespace Oliving.Edge.Controllers 
{
    [ApiController]
    [Route(""api/{ClassName}"")]
    [Authorize(Permissions.Name)]
    public class {ClassName}Controller : " + baseCotroll + @" 
    {
            IMapper _mapper;
            private readonly I{ClassName}Services _{ClassName}Services;
            private readonly ILogger<{ClassName}Controller> _logger;


            public {ClassName}Controller(
                    IHttpContextAccessor accessor, PermissionRequirement requirement,
                    IMapper mapper, ILogger<{ClassName}Controller> logger,
                    I{ClassName}Services {ClassName}Services
                ) : base(accessor, requirement)
            {
                _logger = logger;
                _mapper = mapper;
                _{ClassName}Services = {ClassName}Services;
            }

" + GetControllFunctionTemp_Get() + @"
" + GetControllFunctionTemp_GetPageList_20200403(pkColName) + @"
" + GetControllFunctionTemp_Update(item.Columns) + @"
" + GetControllFunctionTemp_Add() + @"
" + GetControllFunctionTemp_Delete(pkColName) + @"
" + GetControllFunctionTemp_BatchDelete(pkColName) + @"

    }
        }
 
";

                classText = classText.Replace("{ClassName}", item.DbTableName);
                classText = classText.Replace("{Description}", item.Description);

                var filePath = strPath.TrimEnd('\\').TrimEnd('/')
                    + string.Format(Path.DirectorySeparatorChar.ToString() + "{0}Controller.cs", item.DbTableName);
                FileHelper.CreateFile(filePath, classText, Encoding.UTF8);
            }

        }

        #region Controll Function

        public string GetControllFunctionTemp_Get()
        {
            string result = @" 

            [HttpGet]
            [AllowAnonymous]
            [Route(""/api/[controller]/Get"")]
            public async Task<MessageModel<{ClassName}Dto>> Get(string id)
            {
                var data = new MessageModel<{ClassName}Dto>();
                {ClassName} model = await _{ClassName}Services.QueryById(id);
                if (model == null)
                {
                    data.response = null;
                    data.msg = ""数据不存在！"";
                    data.success = false;
                }
                else
                {
                    var dto = _mapper.Map<{ClassName}Dto>(model);
                    data.response = dto;
                    data.msg = ""获取成功！"";
                    data.success = true;
                } 
                return data;
            } 

";

            return result;
        }

        public string GetControllFunctionTemp_GetPageList(string colKey)
        {
            string result = @"

            [HttpGet]
            [Route(""/api/[controller]/GetPageList"")]
            public async Task<MessageModel<PageModel<{ClassName}Dto>>> GetPageList(int page = 1, int intPageSize = 20, string key = """")
            { 
                if (string.IsNullOrEmpty(key) || string.IsNullOrWhiteSpace(key))
                {
                    key = """";
                }

                var data = await _{ClassName}Services.QueryPage(a =>
                                true
                                , page, intPageSize, "" " + colKey + @" desc "");

                var model = _mapper.Map<PageModel<{ClassName}Dto>>(data);

                return new MessageModel<PageModel<{ClassName}Dto>>()
                {
                    msg = ""获取成功"",
                    success = true,
                    response = model
                };
            } 
            ";

            return result;
        }


        public string GetControllFunctionTemp_GetPageList_20200403(string colKey)
        {
            string result = @"

            [HttpGet]
            [Route(""/api/[controller]/GetPageList"")]
            public async Task<MessageModel<PageModel<{ClassName}PageDto>>> GetPageList(int page = 1, int PageSize = 20, string sidx = """", string order = """", string key = """")
            { 
                Expression<Func<{ClassName}, bool>> whereExpression = _{ClassName} => true ;
                if (string.IsNullOrEmpty(key) || string.IsNullOrWhiteSpace(key))
                {
                    key = """";
                }
                else
                {
                 //   whereExpression = whereExpression.And(d =>
                 //           d.Canning_Car.Contains(key) 
                 //       );
                }

                var data = await _{ClassName}Services.QueryPageList(whereExpression, page, PageSize, sidx, order);

                return new MessageModel<PageModel<{ClassName}PageDto>>()
                {
                    msg = ""获取成功"",
                    success = true,
                    response = data
                };
            } 
            ";

            return result;
        }


        public string GetControllFunctionTemp_Update(List<RazorColumnInfo> cols)
        {
            RazorColumnInfo pkCol = cols.FirstOrDefault(F => F.IsPrimarykey);

            StringBuilder sb = new StringBuilder();


            List<RazorColumnInfo> colList = cols.FindAll(F => F.IsPrimarykey == false);

            foreach (RazorColumnInfo dto in colList)
            {
                sb.AppendLine("   model." + dto.DbColumnName + " = dto." + dto.DbColumnName + ";  ");

            }

            string result = @"
 
                [HttpPut]
                [Route(""/api/[controller]/Update"")]
                public async Task<MessageModel<string>> Update([FromBody] {ClassName}Dto dto)
                {
                    var data = new MessageModel<string>();

                    if (dto != null && dto." + pkCol.DbColumnName + @" > 0)
                    {
                        {ClassName} model = await _{ClassName}Services.QueryById(dto." + pkCol.DbColumnName + @");
                        if (model != null)
                        {
                            " + sb.ToString() + @"

                            data.success = await _{ClassName}Services.Update(model);

                            if (data.success)
                            {
                                data.msg = ""更新成功"";
                                data.response = dto." + pkCol.DbColumnName + @".ObjToString();
                            }
                        }
                        else
                        {
                            data.success = false;
                            data.msg = ""参数异常，您要更新的数据不存在"";
                        }
                    }
                    else
                    {
                        data.success = false;
                        data.msg = ""参数异常"";
                    }
                    return data;
                }

            ";

            return result;
        }

        /// <summary>
        ///                     {ClassName}
        /// </summary>
        /// <returns></returns>
        public string GetControllFunctionTemp_Add()
        {
            string result = @"


                [HttpPost]
                [Route(""/api/[controller]/Add"")]
                public async Task<MessageModel<string>> Add({ClassName} dto)
                {
                    var data = new MessageModel<string>();
                    int id = await _{ClassName}Services.AddGuid(dto);

                    data.success = id > 0;
                    if (data.success)
                    {
                        data.response = id.ObjToString();
                        data.msg = ""添加成功"";
                    }
                    return data;
                } 

            ";
            return result;
        }

        /// <summary>
        ///                     {ClassName}
        /// </summary>
        public string GetControllFunctionTemp_Delete(string pkCol)
        {
            string result = @"
 
                [HttpDelete]
                [Route(""/api/[controller]/Delete"")]
                public async Task<MessageModel<string>> Delete(string id)
                {
                    var data = new MessageModel<string>();
                    if (!string.IsNullOrEmpty(id))
                    {
                        var userDetail = await _{ClassName}Services.QueryById(id);
                        // userDetail.C_State = -1; ?????????????
                        data.success = await _{ClassName}Services.Update(userDetail);
                        if (data.success)
                        {
                            data.msg = ""删除成功"";
                            data.response = userDetail?." + pkCol + @".ObjToString();
                        }
                    } 
                    return data;
                }

            ";
            return result;
        }


        /// <summary>
        ///            {ClassName}
        /// </summary>
        /// <returns></returns>
        public string GetControllFunctionTemp_BatchDelete(string pkCol)
        {
            string result = @"


            [HttpDelete]
            [Route(""/api/[controller]/BatchDelete"")]
            public async Task<MessageModel<string>> BatchDelete(string ids)
            {
                var data = new MessageModel<string>();
                if (!string.IsNullOrEmpty(ids))
                {
                    if (false)
                    {
                        #region 软删除

                        int[] list = Array.ConvertAll<string, int>(ids.Split(','), s => int.Parse(s)); 
 
                        {ClassName} model = new {ClassName}();
                        //  model.C_State = -1;          ???????????????????
                        string whereStr = "" " + pkCol + @" in ("" + ids + "")"";
                        List<string> colList = new List<string>();
                        //  colList.Add(""C_State"");    ???????????????????
                        List<string> colHL = new List<string>();
                      
                        bool isOK = await _{ClassName}Services.Update(model, colList, colHL, whereStr);
 
                        data.success = isOK;
                        if (data.success)
                        {
                            data.msg = ""删除成功"";
                            data.response = list.Count().ObjToString();
                        }

                        #endregion
                    }
                    {
                        #region 直接删除 

                        object[] list = Array.ConvertAll<string, object>(ids.Split(','), s => int.Parse(s));

                        bool isOK = await _{ClassName}Services.DeleteByIds(list);

                        data.success = isOK;
                        if (data.success)
                        {
                            data.msg = ""删除成功"";
                            data.response = list.Count().ObjToString();
                        } 
                        #endregion
                    }
                }
                return data;
            }
 

            ";
            return result;
        }



        #endregion

        #endregion


        #region VueView



        public void EdgeCreate_VueView(
          string strPath,
          string strNameSpace,
          string strInterface,
          List<RazorTableInfo> tableList, bool isControllerBase = false)
        {
            //string baseCotroll = isControllerBase ? "OlivingControll" : "ControllerBase";



            foreach (RazorTableInfo item in tableList)
            {
                List<RazorColumnInfo> clist = item.Columns;

                RazorColumnInfo pkCol = item.Columns.FirstOrDefault(F => F.IsPrimarykey);
                string pkColName = pkCol.DbColumnName;

                string classText = @"   
<template>
    <section>

" + EdgeCreate_VueView_Toolbar() + @"
" + EdgeCreate_VueView_Table(clist) + @"
" + EdgeCreate_VueView_PageToolbar() + @"
" + EdgeCreate_VueView_Edit(clist) + @"
" + EdgeCreate_VueView_Add(clist) + @"
 

    </section>
</template>

<script>
" + EdgeCreate_VueView_Script(clist, pkColName) + @"
</script>

<style scoped>
</style>
";

                classText = classText.Replace("{ClassName}", item.DbTableName);
                classText = classText.Replace("{Description}", item.Description);

                var filePath = strPath.TrimEnd('\\').TrimEnd('/')
                    + string.Format(Path.DirectorySeparatorChar.ToString() + "{0}.vue", item.DbTableName);
                FileHelper.CreateFile(filePath, classText, Encoding.UTF8);
            }

        }


        public string EdgeCreate_VueView_Toolbar()
        {
            // getDtoPage
            string result = @"
 
 
                <!--工具条-->
                <el-col :span='24' class='toolbar' style='padding-bottom: 0px;'>
                    <el-form :inline='true' :model='filters' @submit.native.prevent>
                        <el-form-item>
                            <el-input v-model='filters.name' placeholder='名称/Key'></el-input>
                        </el-form-item>
                        <el-form-item>
                            <el-button type='primary' @click='getDtoPage'>查询</el-button>
                        </el-form-item>
                        <el-form-item>
                            <el-button type='primary' @click='handleAdd'>新增</el-button>
                        </el-form-item> 
                        <el-button type='danger' @click='batchRemove' :disabled='this.sels.length===0'>批量删除</el-button> 
                    </el-form>
                </el-col>

";


            return result;
        }

        public string EdgeCreate_VueView_Table(List<RazorColumnInfo> clist)
        {

            StringBuilder sbCols = new StringBuilder();

            foreach (RazorColumnInfo col in clist)
            {
                sbCols.AppendLine($"<el-table-column prop='{col.DbColumnName}' label='{col.ColumnDescription}' width='' sortable>  </el-table-column> ");
            }

            // getUsers
            string result = @"  
         <!--列表-->
         <el-table
:data='users' 
highlight-current-row
v-loading='listLoading' 
@selection-change='selsChange'
                  style='width: 100%;'
                  sortable='custom' @sort-change='sortKey'>

            " + sbCols + @"
             
            <el-table-column label = '操作' width = '150' > 
                <template scope = 'scope' > 
                    <el-button size = 'small' @click = 'handleEdit(scope.$index, scope.row)' > 编辑 </el-button>
                    <el-button type = 'danger' size = 'small' @click = 'handleDel(scope.$index, scope.row)' > 删除 </el-button>
                </template>
            </el-table-column>

         </el-table> 
 ";

            return result;
        }

        public string EdgeCreate_VueView_PageToolbar()
        {
            string result = @"

        <!-- 工具条 ,分页 -->
        <el-col :span='24' class='toolbar'>
            <el-pagination @size-change=""handleSizeChange""
                           @current-change = ""handleCurrentChange""
                           :current-page = ""pageIndex""
                           :page-sizes = ""[ 20, 50, 100]""
                           :page-size = ""pageSize""
                           layout = ""total, sizes, prev, pager, next, jumper""
                           :total = ""total""
                           style = 'float:right;' >
            </el-pagination>
        </el-col>

";
            return result;
        }

        public string EdgeCreate_VueView_Edit(List<RazorColumnInfo> clist)
        {

            StringBuilder sb = new StringBuilder();

            foreach (RazorColumnInfo col in clist)
            {
                sb.AppendLine(@"
                     <el-form-item label='" + col.ColumnDescription + @"' prop='" + col.DbColumnName + @"'>
                          <el-input v-model='editForm." + col.DbColumnName + @"' auto-complete='off'></el-input>
                     </el-form-item>
                ");
            }

            string result = @" 
                <!--编辑界面-->
                <el-dialog title='编辑' :visible.sync='editFormVisible' v-model='editFormVisible' :close-on-click-modal='false'>
                    <el-form :model='editForm' label-width='80px' :rules='editFormRules' ref='editForm'>
                         " + sb + @"
                    </el-form>
                    <div slot='footer' class='dialog-footer'>
                        <el-button @click.native='editFormVisible = false'>取消</el-button>
                        <el-button type='primary' @click.native='editSubmit' :loading='editLoading'>提交</el-button>
                    </div>
                </el-dialog> 
";
            return result;
        }

        public string EdgeCreate_VueView_Add(List<RazorColumnInfo> clist)
        {
            StringBuilder sb = new StringBuilder();

            foreach (RazorColumnInfo col in clist)
            {
                sb.AppendLine(@"
                    <el-form-item label='" + col.ColumnDescription + @"' prop='" + col.DbColumnName + @"'>
                        <el-input v-model='addForm." + col.DbColumnName + @"' auto-complete='off'></el-input>
                    </el-form-item>
                ");
            }

            string result = @"

        <!--新增界面-->
        <el-dialog title='新增' :visible.sync='addFormVisible' v-model='addFormVisible' :close-on-click-modal='false'>
            <el-form :model='addForm' label-width='80px' :rules='addFormRules' ref='addForm'>

               
            " + sb + @"

            </el-form>
            <div slot='footer' class='dialog-footer'>
                <el-button @click.native='addFormVisible = false'>取消</el-button>
                <el-button type='primary' @click.native='addSubmit' :loading='addLoading'>提交</el-button>
            </div>
        </el-dialog>


";
            return result;
        }

        /// <summary>
        ///            {ClassName}
        /// </summary>
        public string EdgeCreate_VueView_Script(List<RazorColumnInfo> clist, string pkName)
        {

            StringBuilder edgeEditFormRules = new StringBuilder();
            StringBuilder edgeEditForm = new StringBuilder();

            edgeEditFormRules.Append("{");
            edgeEditForm.Append("{");

            StringBuilder edgeAddFormRules = new StringBuilder();
            StringBuilder edgeAddForm = new StringBuilder();

            edgeAddFormRules.Append("{");
            edgeAddForm.Append("{");



            foreach (RazorColumnInfo item in clist)
            {
                edgeEditFormRules.AppendLine("      " + item.DbColumnName + ": [{ required: true, message: '请输入" + item.ColumnDescription + "', trigger: 'blur' }] ,     ");
                edgeAddFormRules.AppendLine("      " + item.DbColumnName + ": [{ required: true, message: '请输入" + item.ColumnDescription + "', trigger: 'blur' }] ,     ");



                string typeValyue = "";
                switch (item.DataType.ToLower())
                {
                    case "string": typeValyue = "''"; break;
                    case "datetime": typeValyue = "null"; break;
                    default: typeValyue = "0"; break;
                }

                edgeEditForm.AppendLine("      " + item.DbColumnName + ":" + typeValyue + ",    ");
                if (!item.IsPrimarykey)
                {
                    edgeAddForm.AppendLine("      " + item.DbColumnName + ":" + typeValyue + ",    ");
                }

            }

            edgeEditFormRules.AppendLine("}");
            edgeEditForm.AppendLine("}");

            edgeAddFormRules.AppendLine("}");
            edgeAddForm.AppendLine("}");


            #region MyRegion

            string result = @"
                import util from '../../../util/date'
                import { testapi, getPage_{ClassName}, getByID_{ClassName} ,edit_{ClassName}, add_{ClassName}, batchRemove_{ClassName}, Remove_{ClassName}  } from '../../api/api';

                export default { 
                     data() {   // 全局变量
                            return {
                                filters: { name: '' },
                                users: [],
                                //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
                                total: 0,
                                pageSize: 20,
                                pageIndex: 1, 
                                sidx: null,   //  排序字段
                                order: null,  //  排序方式， 正序\倒序
                                //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
                                listLoading: false,
                                sels: [],//列表选中列
                                addDialogFormVisible: false,
                                editFormVisible: false,//编辑界面是否显示
                                editLoading: false,
                                editFormRules: " + edgeEditFormRules + @" ,
                                //编辑界面数据
                                editForm: " + edgeEditForm + @", 
                                addFormVisible: false,//新增界面是否显示
                                addLoading: false,
                                addFormRules:  " + edgeAddFormRules + @",
                                //新增界面数据
                                addForm: " + edgeAddForm + @" 
                                     }
                              },
                    methods: {    // 全局方法
                        //性别显示转换
                        //formatSex: function (row, column) {
                        //    return row.C_Value == 2 ? '男' : row.C_Value;
                        //},
                        //formatterCreateTime: function (row, column) {
                        //    return (!row.C_CreateTime || row.C_CreateTime == '') ? '' : util.formatDate.format(new Date(row.C_CreateTime), 'yyyy-MM-dd');
                        //},
                        handleCurrentChange(val) {
                            this.page = val;
                            this.getDtoPage();
                        }, 
                        // 测试
                        sortKey(val) {
                            console.log(val)
                        },
                        // 每页数
                            handleSizeChange(val) {
                                this.pageSize = val;
                                this.pageIndex = 1;
                                this.getDtoPage();
                            },

                        //获取用户列表
                        getDtoPage() { 
                            let para = {
                                page: this.pageIndex,
                                pageSize: this.pageSize,
                                key: this.filters.name,
                                sidx: this.sidx,
                                order: this.order
                            };
                            this.listLoading = true;
  
                            getPage_{ClassName}(para).then((res) => {
                                console.log(res);
                                this.total = res.data.response.dataCount;
                                this.users = res.data.response.data;
                                this.listLoading = false;

                            });
                        },
                        //删除
                        handleDel: function (index, row) {
                            this.$confirm('确认删除该记录吗?', '提示', {
                                confirmButtonText: '确定',
                                cancelButtonText: '取消',
                                type: 'warning'
                            }).then(() => {
                                this.listLoading = true;
                                let para = { id: row." + pkName + @" };
                                 Remove_{ClassName}(para).then((res) => {
                                    if (util.isEmt.format(res)) {
                                        this.listLoading = false;
                                        return;
                                    }
                                    this.listLoading = false;
                                    if (res.data.success) {
                                        this.$message({
                                            message: '删除成功',
                                            type: 'success'
                                        });
                                    } else {
                                        this.$message({
                                            message: res.data.msg,
                                            type: 'error'
                                        });
                                    }
                                    this.getDtoPage();
                                });
                            }).catch((c) => {
                                console.log(c);
                            });
                        },
                        //显示编辑界面
                        handleEdit: function (index, row) {
                            this.editFormVisible = true;

                            let para_getGetByID = { id: row." + pkName + @" };

                           getByID_{ClassName}(para_getGetByID).then((getDto) => {

                                this.editForm = Object.assign({}, getDto.data.response);
                            });
                        },
                        //显示新增界面
                        handleAdd() {
                            this.addFormVisible = true;
                            this.addForm = " + edgeAddForm + @";
                        },
                        //编辑
                        editSubmit: function () {
                            this.$refs.editForm.validate((valid) => {
                                if (valid) {
                                    this.$confirm('确认提交吗？', '提示', {
                                        confirmButtonText: '确定',
                                        cancelButtonText: '取消',
                                    }).then(() => {
                                        this.editLoading = true;
                                        //NProgress.start();
                                        let para = Object.assign({}, this.editForm);
                                        console.log(para);
                                        edit_{ClassName}(para).then((res) => {

                                            if (util.isEmt.format(res)) {
                                                this.editLoading = false;
                                                return;
                                            }
                                            if (res.data.success) {
                                                this.editLoading = false;
                                               
                                                this.$message({
                                                    message: res.data.msg,
                                                    type: 'success'
                                                });
                                                this.$refs['editForm'].resetFields();
                                                this.editFormVisible = false;
                                                this.getDtoPage();
                                            } else {
                                                this.$message({
                                                    message: res.data.msg,
                                                    type: 'error'
                                                });
                                            }
                                        });
                                    });
                                }
                            });
                        },
                        //新增
                        addSubmit: function () {
                            this.$refs.addForm.validate((valid) => {
                                if (valid) {
                                    this.$confirm('确认提交吗？', '提示', {
                                        confirmButtonText: '确定',
                                        cancelButtonText: '取消',
                                    }).then(() => {
                                        this.addLoading = true;
                                        let para = Object.assign({}, this.addForm);

                                        add_{ClassName}(para).then((res) => {

                                            if (util.isEmt.format(res)) {
                                                this.addLoading = false;
                                                return;
                                            }

                                            if (res.data.success) {
                                                this.addLoading = false;
                                                this.$message({
                                                    message: res.data.msg,
                                                    type: 'success'
                                                });
                                                this.$refs['addForm'].resetFields();
                                                this.addFormVisible = false;
                                                this.getDtoPage();
                                            }
                                            else {
                                                this.$message({
                                                    message: res.data.msg,
                                                    type: 'error'
                                                });
                                            }
                                        });
                                    });
                                }
                            });
                        },
                        selsChange: function (sels) {
                            this.sels = sels;
                        },
                        //批量删除
                        batchRemove: function () {

                            var ids = this.sels.map(item => item." + pkName + @").toString();
                            this.$confirm('确认删除选中记录吗？', '提示', {
                                type: 'warning',
                                confirmButtonText: '确定',
                                cancelButtonText: '取消'
                            }).then(() => {
                                this.listLoading = true; 
                                let para = { ids: ids };

                                batchRemove_{ClassName}(para).then((res) => {
                                    this.listLoading = false;
 
                                    if (res.data.success) {
                                        this.$message({
                                            message: '删除成功',
                                            type: 'success'
                                        });
                                    } else {
                                        this.$message({
                                            message: res.data.msg,
                                            type: 'error'
                                        });
                                    }
                                    this.getDtoPage();
                                    console.log(res)
                                });
                            }).catch(() => {

                            });
                        }
                    },
                    mounted() {
                        this.getDtoPage();
        }
                      } 
";

            #endregion


            return result;
        }

        #endregion




        public void EdgeCreate_VueApi(string strPath, List<RazorTableInfo> tableList)
        {
            var seChar = Path.DirectorySeparatorChar.ToString();
            foreach (RazorTableInfo item in tableList)
            {

                //  get{ClassName}Page, get{ClassName}GetByID, edit{ClassName}, add{ClassName}, batchRemove{ClassName}, Remove{ClassName} }
                string classText = @"

// {ClassDescription}
export const getPage_{ClassName} = params => {
    return axios.get(`${base}/api/{ClassName}/GetPageList`, { params: params });
};

export const getByID_{ClassName} = params => {
    return axios.get(`${base}/api/{ClassName}/Get`, { params: params });
};

export const edit_{ClassName} = params => {
    return axios.put(`${base}/api/{ClassName}/Update`, params);
};

export const add_{ClassName} = params => {
    return axios.post(`${base}/api/{ClassName}/Add`, params);
};


export const batchRemove_{ClassName} = params => {
    return axios.delete(`${base}/api/{ClassName}/BatchDelete`, { params: params });
};

export const Remove_{ClassName} = params => {
    return axios.delete(`${base}/api/{ClassName}/delete`, { params: params }); 
};

";

                classText = classText.Replace(DbFirstTemplate.KeyClassDescription, item.Description);

                classText = classText.Replace("{ClassName}", item.DbTableName);


                var filePath = strPath.TrimEnd('\\').TrimEnd('/') + string.Format(seChar + "{0}.txt", item.DbTableName);
                FileHelper.CreateFile(filePath, classText, Encoding.UTF8);
            }
        }




        public void InsertfunctionData(EdgeContext myContext, string TableName, string TableRemark)
        {
            List<Module> list = new List<Module>();

            #region 分页

            list.Add(new Module
            {
                Name = $"【{TableName}/{TableRemark}】分页",
                LinkUrl = $"/api/{TableName}/GetPageList",
                Area = "api",
                Controller = TableName,
                Action = "GetPageList",
                OrderSort = 1,
                IsDeleted = false,
                Enabled = true,
                CreateTime = DateTime.Now
            });
            #endregion

            #region Add

            list.Add(new Module
            {
                Name = $"【{TableName}/{TableRemark}】添加",
                LinkUrl = $"/api/{TableName}/Add",
                Area = "api",
                Controller = TableName,
                Action = "Add",
                OrderSort = 1,
                IsDeleted = false,
                Enabled = true,
                CreateTime = DateTime.Now
            });

            #endregion

            #region 详情

            list.Add(new Module
            {
                Name = $"【{TableName}/{TableRemark}】详情",
                LinkUrl = $"/api/{TableName}/Get",
                Area = "api",
                Controller = TableName,
                Action = "Get",
                OrderSort = 1,
                IsDeleted = false,
                Enabled = true,
                CreateTime = DateTime.Now
            });
            #endregion

            #region 更新

            list.Add(new Module
            {
                Name = $"【{TableName}/{TableRemark}】更新",
                LinkUrl = $"/api/{TableName}/Update",
                Area = "api",
                Controller = TableName,
                Action = "Update",
                OrderSort = 1,
                IsDeleted = false,
                Enabled = true,
                CreateTime = DateTime.Now
            });
            #endregion

            #region 删除

            list.Add(new Module
            {
                Name = $"【{TableName}/{TableRemark}】删除",
                LinkUrl = $"/api/{TableName}/Delete",
                Area = "api",
                Controller = TableName,
                Action = "Delete",
                OrderSort = 1,
                IsDeleted = false,
                Enabled = true,
                CreateTime = DateTime.Now
            });
            #endregion

            #region 批量删除

            list.Add(new Module
            {
                Name = $"【{TableName}/{TableRemark}】批量删除",
                LinkUrl = $"/api/{TableName}/BatchDelete",
                Area = "api",
                Controller = TableName,
                Action = "BatchDelete",
                OrderSort = 1,
                IsDeleted = false,
                Enabled = true,
                CreateTime = DateTime.Now
            });
            #endregion

            myContext.GetEntityDB<Module>().InsertRange(list);

            Console.WriteLine($"生成接口数据【{TableName}/{TableRemark}】");
        }

        public void InsertfunctionData_Page(EdgeContext myContext, string groupMenuCode, string groupMenuName, string TableName, string TableRemark)
        {
            Permission groupName = myContext.GetEntityDB<Permission>().GetList().FirstOrDefault(T => T.IsButton == false && T.Enabled == true && T.IsDeleted == false && T.Name == groupMenuName);
            int groupID = 0;
            if (groupName == null)
            {
                Permission groupDto = new Permission
                {
                    Code = "-",
                    Name = groupMenuName,
                    IsButton = false,
                    Pid = 0,
                    Mid = 0,
                    Description = groupMenuName,
                    CreateTime = DateTime.Now,
                    ModifyTime = DateTime.Now,
                    Enabled = true,
                    IsDeleted = false
                };
                groupID = myContext.GetEntityDB<Permission>().InsertReturnIdentity(groupDto);

            }
            else
            {
                groupID = groupName.Id;
            }

            #region page 

            Module dtoGetPageList = (new Module
            {
                Name = $"【{TableName}/{TableRemark}】分页",
                LinkUrl = $"/api/{TableName}/GetPageList",
                Area = "api",
                Controller = TableName,
                Action = "GetPageList",
                OrderSort = 1,
                IsDeleted = false,
                Enabled = true,
                CreateTime = DateTime.Now
            });

            int pkid = myContext.GetEntityDB<Module>().InsertReturnIdentity(dtoGetPageList);

            Permission dtoPermPageList = new Permission
            {
                Code = $"/{groupMenuCode}/{TableName}",
                Name = TableRemark,
                IsButton = false,
                Pid = groupID,
                Mid = pkid,
                Description = $"{TableRemark}",
                CreateTime = DateTime.Now,
                ModifyTime = DateTime.Now,
                Enabled = true,
                IsDeleted = false
            };
            int menuID = myContext.GetEntityDB<Permission>().InsertReturnIdentity(dtoPermPageList);

            #endregion

            #region 详情 

            Module xiangQing = (new Module
            {
                Name = $"【{TableName}/{TableRemark}】详情",
                LinkUrl = $"/api/{TableName}/Get",
                Area = "api",
                Controller = TableName,
                Action = "Get",
                OrderSort = 1,
                IsDeleted = false,
                Enabled = true,
                CreateTime = DateTime.Now
            });

            myContext.GetEntityDB<Module>().InsertReturnIdentity(xiangQing);

            #endregion

            #region Add

            Module dtoMAdd = (new Module
            {
                Name = $"【{TableName}/{TableRemark}】添加",
                LinkUrl = $"/api/{TableName}/Add",
                Area = "api",
                Controller = TableName,
                Action = "Add",
                OrderSort = 1,
                IsDeleted = false,
                Enabled = true,
                CreateTime = DateTime.Now
            });

            int pkid_Add = myContext.GetEntityDB<Module>().InsertReturnIdentity(dtoMAdd);

            Permission dtoPAdd = new Permission
            {
                Code = "-",
                Name = "添加",
                IsButton = true,
                Pid = menuID,
                Mid = pkid_Add,
                Description = $"{TableRemark}",
                CreateTime = DateTime.Now,
                ModifyTime = DateTime.Now,
                Enabled = true,
                IsDeleted = false
            };
            myContext.GetEntityDB<Permission>().InsertReturnIdentity(dtoPAdd);

            #endregion

            #region 更新

            Module dtoMUpdate = (new Module
            {
                Name = $"【{TableName}/{TableRemark}】更新",
                LinkUrl = $"/api/{TableName}/Update",
                Area = "api",
                Controller = TableName,
                Action = "Update",
                OrderSort = 1,
                IsDeleted = false,
                Enabled = true,
                CreateTime = DateTime.Now
            });
            int pkid_Update = myContext.GetEntityDB<Module>().InsertReturnIdentity(dtoMUpdate);

            Permission dtoPUpdate = new Permission
            {
                Code = "-",
                Name = "更新",
                IsButton = true,
                Pid = menuID,
                Mid = pkid_Update,
                Description = $"{TableRemark}",
                CreateTime = DateTime.Now,
                ModifyTime = DateTime.Now,
                Enabled = true,
                IsDeleted = false
            };
            myContext.GetEntityDB<Permission>().InsertReturnIdentity(dtoPUpdate);


            #endregion

            #region 删除

            Module dtoMDel = (new Module
            {
                Name = $"【{TableName}/{TableRemark}】删除",
                LinkUrl = $"/api/{TableName}/Delete",
                Area = "api",
                Controller = TableName,
                Action = "Delete",
                OrderSort = 1,
                IsDeleted = false,
                Enabled = true,
                CreateTime = DateTime.Now
            });

            int pkid_del = myContext.GetEntityDB<Module>().InsertReturnIdentity(dtoMDel);

            Permission dtoPdel = new Permission
            {
                Code = "-",
                Name = "删除",
                IsButton = true,
                Pid = menuID,
                Mid = pkid_del,
                Description = $"{TableRemark}",
                CreateTime = DateTime.Now,
                ModifyTime = DateTime.Now,
                Enabled = true,
                IsDeleted = false
            };
            myContext.GetEntityDB<Permission>().InsertReturnIdentity(dtoPdel);



            #endregion

            #region 批量删除

            Module dtoMBD = (new Module
            {
                Name = $"【{TableName}/{TableRemark}】批量删除",
                LinkUrl = $"/api/{TableName}/BatchDelete",
                Area = "api",
                Controller = TableName,
                Action = "BatchDelete",
                OrderSort = 1,
                IsDeleted = false,
                Enabled = true,
                CreateTime = DateTime.Now
            });

            int pkid_MBD = myContext.GetEntityDB<Module>().InsertReturnIdentity(dtoMBD);

            Permission dtoPBD = new Permission
            {
                Code = "-",
                Name = "批量删除",
                IsButton = true,
                Pid = menuID,
                Mid = pkid_MBD,
                Description = $"{TableRemark}",
                CreateTime = DateTime.Now,
                ModifyTime = DateTime.Now,
                Enabled = true,
                IsDeleted = false
            };

            myContext.GetEntityDB<Permission>().InsertReturnIdentity(dtoPBD);

            #endregion

        }


        #region MyRegion


        public void EdgeCreate_AutoMapper(string strPath, List<RazorTableInfo> tableList)
        {
            var seChar = Path.DirectorySeparatorChar.ToString();
            foreach (RazorTableInfo item in tableList)
            {
                string classText = @" 
                    CreateMap<{ClassName}, {ClassName}Dto>();
                    CreateMap<{ClassName}Dto, {ClassName}>();
                    CreateMap<PageModel<{ClassName}>, PageModel<{ClassName}Dto>>(); 
                ";

                classText = classText.Replace(DbFirstTemplate.KeyClassDescription, item.Description);
                classText = classText.Replace("{ClassName}", item.DbTableName);

                var filePath = strPath.TrimEnd('\\').TrimEnd('/') + string.Format(seChar + "AutoMapper_{0}.txt", item.DbTableName);
                FileHelper.CreateFile(filePath, classText, Encoding.UTF8);
            }
        }



        #endregion

    }
}